package com.xy.yunduo.utils.response;

import com.xy.yunduo.utils.JsonUtil;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class ServerResponseUtil {
    public static <T> ApiResponse<T> replyError(ErrorCode errorCode){

        ApiResponse<T> apiResponse = new ApiResponse<T>();

        apiResponse.setCode(errorCode.code);
        apiResponse.setMessage( MessageHolder.get(errorCode.message));
        return apiResponse;
    }
    public static <T> ApiResponse<T> replySuccess(){
        ApiResponse<T> apiResponse = new ApiResponse<T>();
        ErrorCode errorCode = CommonErrorCodes.REQUEST_SUCCESS;
        apiResponse.setCode(errorCode.code);
        apiResponse.setMessage(MessageHolder.get(errorCode.message));
        return apiResponse;
    }
    public static <T> ApiResponse<T> replySuccess(Class<T> type){

        ApiResponse<T> apiResponse = new ApiResponse<T>();
        T t = null;
        try {
            t = type.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

        ErrorCode errorCode = CommonErrorCodes.REQUEST_SUCCESS;
        apiResponse.setCode(errorCode.code);
        apiResponse.setMessage(MessageHolder.get(errorCode.message));
        apiResponse.setData(t);

        SortedMap<String, Object> sortedMap = new TreeMap();
        sortedMap.put("data", JsonUtil.dump(t));

        return apiResponse;
    }
    public static <T> ApiResponse<T> replySuccess(T t){

        ApiResponse<T> apiResponse = new ApiResponse<T>();
        ErrorCode errorCode = CommonErrorCodes.REQUEST_SUCCESS;
        apiResponse.setCode(errorCode.code);
        apiResponse.setMessage(MessageHolder.get(errorCode.message));
        apiResponse.setData(t);
        return apiResponse;
    }
    public static <T> ApiPagerResponse<T> replySuccess(long total,List<T> list){

        ApiPagerResponse<T> apiResponse = new ApiPagerResponse<T>();
        ErrorCode errorCode = CommonErrorCodes.REQUEST_SUCCESS;
        apiResponse.setCode(errorCode.code);
        apiResponse.setMessage(MessageHolder.get(errorCode.message));
        PagerBody<T> body=new PagerBody<>();
        body.setList(list);
        body.setTotal(total);
        apiResponse.setData(body);
        return apiResponse;
    }
}
